package jdbc;

import java.sql.*;

/**
 * 测试批处理的基本用法(Batch)
 * 对于大量的批处理,建议使用Statement,因为PreparedStatement的预编译空间有限
 * 当数据特别大时会出现异常
 */
public class Demo05 {
    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            //加载驱动类
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testjdbc?serverTimezone=Asia/Shanghai", "root", "123456");
            conn.setAutoCommit(false);//将事务设为手动提交(jdbc中的是自动提交的)

            stmt=conn.createStatement();

            for (int i=11;i<20011;i++){
                //stmt.addBatch("insert into t_user (username,pwd,regTime) values ('李"+i+"',666666,now())");
                //stmt.addBatch("delete from t_user where id='"+i+"'");//删除表中数据
            }
            stmt.executeBatch();//执行批处理

            conn.commit();//提交事务
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
